package com.wenshi.web.controller.device;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wenshi.common.core.controller.BaseController;
import com.wenshi.common.core.domain.AjaxResult;
import com.wenshi.common.core.domain.R;
import com.wenshi.common.core.page.TableDataInfo;
import com.wenshi.common.utils.DateUtils;
import com.wenshi.common.utils.StringUtils;
import com.wenshi.system.domain.DeviceData;
import com.wenshi.system.domain.SysDevice;
import com.wenshi.system.domain.vo.request.UpdateDeviceRequest;
import com.wenshi.system.service.DeviceDataService;
import com.wenshi.system.service.ISysDeviceService;
import com.wenshi.web.controller.tool.TranToSysDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/device")
public class SysDeviceController extends BaseController {
    @Autowired
    ISysDeviceService sysDeviceService;
    @Autowired
    com.wenshi.web.service.webService webService;
    @Autowired
    DeviceDataService deviceDataService;

    @GetMapping("/list")
    public TableDataInfo getDeviceList(SysDevice sysDevice){
        startPage();
        String deviceName = sysDevice.getDeviceName();
        List<SysDevice> list=null;
        if (StringUtils.isNotEmpty(deviceName)) {
            QueryWrapper<SysDevice> sysDeviceQueryWrapper = new QueryWrapper<>();
            sysDeviceQueryWrapper.like("device_name",deviceName);
             list = sysDeviceService.list(sysDeviceQueryWrapper);

        }else {
             list = sysDeviceService.list();
        }
//        SysDevice sysDevice = new SysDevice(2L,"sasa","ss","127.0.0.1",502L,"sz","2024-06-05 14:01:13");
//        list.add(sysDevice);
        return  getDataTable(list);
    }
    @PutMapping("/update")
    public R updateDevice(@Validated  @RequestBody UpdateDeviceRequest deviceRequest){
        Long deviceId = deviceRequest.getDeviceId();
        SysDevice sysDevice = new SysDevice();
        if (deviceId!=null){
            sysDevice.setDeviceId(deviceId);
        }
        sysDevice.setDeviceId(deviceRequest.getDeviceId());
        sysDevice.setDeviceName(deviceRequest.getDeviceName());
        sysDevice.setDeviceType(deviceRequest.getDeviceType());
        sysDevice.setDeviceIp(deviceRequest.getDeviceIp());
        sysDevice.setDevicePort(deviceRequest.getDevicePort());
        sysDevice.setDeviceArea(deviceRequest.getDeviceArea());
        if (deviceId==null){
            sysDevice.setCreateTime(DateUtils.getTime());
            sysDevice.setDeviceStatus(false);
        }
        boolean b = sysDeviceService.saveOrUpdate(sysDevice);
        if (b){
            return R.ok();
        }
        return R.fail();
    }
    @GetMapping("/get/{deviceId}")
    public AjaxResult getSysDeviceById(@PathVariable String deviceId){
        SysDevice deviceServiceById = sysDeviceService.getById(deviceId);
        AjaxResult result = AjaxResult.success(deviceServiceById);
        return result;
    }
    @DeleteMapping("/delete/{deviceId}")
    public AjaxResult deleteDeviceByIds(@PathVariable Long[] deviceId){
        List<Long> deleteIds = Arrays.stream(deviceId).collect(Collectors.toList());
        boolean b = sysDeviceService.removeByIds(deleteIds);
        return toAjax(b);
    }

    @PostMapping("/connect")
    public DeferredResult<AjaxResult> connectDeviceByAddress(@Validated  @RequestBody UpdateDeviceRequest deviceRequest){
        DeferredResult<AjaxResult> deferredResult = new DeferredResult<>(5000L);
        SysDevice sysDevice = TranToSysDevice.tranToSysDevice(deviceRequest);
        CompletableFuture<AjaxResult> futureResult  = webService.connectDeviceByAddress(sysDevice);
        futureResult.whenComplete((result, throwable) -> {
            if (throwable != null) {
                // 异常处理
                deferredResult.setErrorResult(AjaxResult.error("连接失败"));
            } else {
                // 成功结果处理
                deferredResult.setResult(result);
            }
        });
        deferredResult.onTimeout(() -> deferredResult.setErrorResult(AjaxResult.error("连接失败,设备未在线")));
        return  deferredResult;
    }
    public R updateDeviceByIp(String ip,Boolean status){
         sysDeviceService.updateDeviceByIp(ip,status);
            return R.ok();
    }
    @GetMapping("/getDeviceData")
    @CrossOrigin
    public AjaxResult getDeviceData(String deviceIp){
        SysDevice byDeviceIp = sysDeviceService.getByDeviceIp(deviceIp);
        Long deviceId = byDeviceIp.getDeviceId();
        List<DeviceData> list = deviceDataService.selectAllDeviceData(deviceId);
        return AjaxResult.success(list);
    }
}
